﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using CRM.Entity;
using CRM.BLL;
using DP.Web.UI;
using DP.Common;
using System.Text;

namespace CRM.Web.SurveyManage
{
    public partial class Survey : Common.PageBase
    {
        public string ModifyUrl = "Survey.aspx?SURVEY_ID={0}&AUTOID={1}";
        T_SURVEY_BLL sBll = new T_SURVEY_BLL();
        T_SURVEY_ITEM_BLL iBll = new T_SURVEY_ITEM_BLL();
        T_SURVEY_ITEM_OPTION_BLL siopBll = new T_SURVEY_ITEM_OPTION_BLL();
        T_SURVEY_ITEMS_BLL isBll = new T_SURVEY_ITEMS_BLL();
        T_SURVEY_OPTIONS_BLL isopBll = new T_SURVEY_OPTIONS_BLL();
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            gvList.PageSize = 10;
            gvList_items.PageSize = 10;
            PageHelper.SetPrePageUrl(this.Page);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                EnumHelper.FillListControl(ddlITEM_TYPE, typeof(ItemType));
                string surveyid = PageHelper.GetQueryString(this.Page, "SURVEY_ID");
                string itemautoid = PageHelper.GetQueryString(this.Page, "AUTOID");
                pageDataInit(surveyid, itemautoid);
                gvDataBinding();
            }
        }

        private void pageDataInit(string surveyid, string itemautoid)
        {
            if (!String.IsNullOrEmpty(surveyid))
            {
                T_SURVEY_Entity entity = new T_SURVEY_Entity();
                entity = sBll.GetEntity("SURVEY_ID", StringHelper.ToInt(surveyid));
                if (entity == null) return;
                PageHelper.SetControlValue(this.plSURVEY, entity);
            }
            if (!String.IsNullOrEmpty(itemautoid))
            {
                T_SURVEY_ITEM_Entity entity = new T_SURVEY_ITEM_Entity();
                entity = iBll.GetEntity("AUTOID", StringHelper.ToInt(itemautoid));
                if (entity == null) return;
                PageHelper.SetControlValue(this.plITEMS, entity);
                txtSURVEY_ID1.Text = entity.SURVEY_ID.ToString();
                txtSURVEY_NAME.Text = txtSNAME.Text;
            }
        }

        /// <summary>
        /// 页面数据绑定
        /// </summary>
        private void gvDataBinding()
        {
            #region 查询条件字符串
            StringBuilder sql = new StringBuilder();
            #endregion
            if (!UserLoginInfo.IsAdministrator())
            {
                sql.Append(" and BUSINESSDIVISIONCODE = '" + _userLoginInfo.UserEntity.BUSINESSDIVISIONCODE.Trim() + "'");
            }
            List<T_SURVEY_Entity> list;
            //获取总的记录条数
            gvList.RecordCount = (int)sBll.GetCount(sql.ToString());
            list = sBll.GetList(sql.ToString(), gvList.CurrentPageIndex * gvList.PageSize, gvList.PageSize, gvList.SortConditions);
            gvList.DataSource = list;
            gvList.DataKeyNames = new string[] { "SURVEY_ID" };
            gvList.DataBind();

            if (!String.IsNullOrEmpty(PageHelper.GetQueryString(this.Page, "SURVEY_ID")))
            {
                sql.Append(" AND SURVEY_ID='" + PageHelper.GetQueryString(this.Page, "SURVEY_ID") + "'");
            }
            List<T_SURVEY_ITEM_Entity> listOptions;
            gvList_items.RecordCount = (int)iBll.GetCount(sql.ToString());
            listOptions = iBll.GetList(sql.ToString(), gvList_items.CurrentPageIndex * gvList_items.PageSize, gvList_items.PageSize, gvList_items.SortConditions);
            gvList_items.DataSource = listOptions;
            gvList_items.DataKeyNames = new string[] { "AUTOID" };
            gvList_items.DataBind();
        }

        /// <summary>
        /// 新建问卷、题目
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnAdd_Click(object sender, EventArgs e)
        {
            if (sender == btnAdd)
            {
                txtSURVEY_ID.Text = "";
                txtSNAME.Text = "";
                txtSDATE.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                txtSINFO.Text = "";
                txtGHID.Text = _userLoginInfo.UserEntity.USERID.ToString();
            }
            else if (sender == btnAdd_ITEM)
            {
                string itemid = iBll.GetMaxValue("ITEM_ID", " AND SURVEY_ID='" + txtSURVEY_ID.Text + "'");
                int i = 1;
                if (!String.IsNullOrEmpty(itemid))
                {
                    i = StringHelper.ToInt(itemid) + 1;
                }
                txtITEM_ID.Text = i.ToString();
                txtITEM_NAME.Text = "";
                txtSURVEY_ID1.Text = txtSURVEY_ID.Text;
                txtSURVEY_NAME.Text = txtSNAME.Text;
                ddlITEM_TYPE.SelectedValue = ((int)ItemType.单选).ToString();
                rbENINPUT0.Checked = true;
                rbENNULL0.Checked = true;
                txtIINFO.Text = "";
            }
        }

        /// <summary>
        /// 保存数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnOK_Click(object sender, EventArgs e)
        {
            if (sender == this.btnOK)
            {
                T_SURVEY_Entity entity = new T_SURVEY_Entity();
                if (txtSNAME.Text == "")
                {
                    PageHelper.ShowMessage(this.Page, "问卷名称不能为空！");
                    return;
                }
                entity = sBll.GetEntity("SURVEY_ID", txtSURVEY_ID.Text);
                if (entity == null)
                {
                    entity = sBll.GetEntity("SNAME", txtSNAME.Text);
                    if (entity == null)
                    {
                        entity = new T_SURVEY_Entity();
                        PageHelper.GetControlValue<T_SURVEY_Entity>(this.plSURVEY, ref entity);
                        entity.BUSINESSDIVISIONCODE = _userLoginInfo.UserEntity.BUSINESSDIVISIONCODE;
                        entity.BUSINESSDIVISIONID = _userLoginInfo.UserEntity.BUSINESSDIVISIONID;
                        entity.BUSINESSDIVISIONNAME = _userLoginInfo.UserEntity.BUSINESSDIVISIONNAME;
                        sBll.Insert(entity);
                    }
                    else
                    {
                        PageHelper.ShowMessage(this.Page, "问卷名称已经存在，请核实后再进行增加");
                        return;
                    }
                }
                else
                {
                    PageHelper.GetControlValue<T_SURVEY_Entity>(this.plSURVEY, ref entity);
                    sBll.Update(entity);
                }
                PageHelper.ShowMessage(this.Page, "保存成功！");
                Response.Redirect(HttpContext.Current.Request.RawUrl);
            }
            else if (sender == this.btnOK_ITEM)
            {
                if (txtITEM_ID.Text == "")
                {
                    PageHelper.ShowMessage(this.Page, "题目编号不能为空！");
                    return;
                }
                if (!String.IsNullOrEmpty(txtSELECTITEMS.Text))
                {
                    Save_from_Items();
                    Response.Redirect(HttpContext.Current.Request.RawUrl);
                    return;
                }
                if (txtITEM_NAME.Text == "")
                {
                    PageHelper.ShowMessage(this.Page, "题目名称不能为空！");
                    return;
                }
                List<T_SURVEY_ITEM_Entity> list = new List<T_SURVEY_ITEM_Entity>();
                T_SURVEY_ITEM_Entity entity = new T_SURVEY_ITEM_Entity();
                list = iBll.GetList(string.Format(" AND ITEM_ID='{0}' AND SURVEY_ID='{1}'", txtITEM_ID.Text, txtSURVEY_ID1.Text));
                if (list.Count == 0)
                {
                    PageHelper.GetControlValue<T_SURVEY_ITEM_Entity>(this.plITEMS, ref entity);
                    entity.ITEM_TYPE = StringHelper.ToInt(ddlITEM_TYPE.SelectedValue);
                    entity.SURVEY_ID = StringHelper.ToInt(txtSURVEY_ID1.Text);
                    entity.BUSINESSDIVISIONCODE = _userLoginInfo.UserEntity.BUSINESSDIVISIONCODE;
                    entity.BUSINESSDIVISIONID = _userLoginInfo.UserEntity.BUSINESSDIVISIONID;
                    entity.BUSINESSDIVISIONNAME = _userLoginInfo.UserEntity.BUSINESSDIVISIONNAME;
                    iBll.Insert(entity);
                }
                else
                {
                    entity.AUTOID = list[0].AUTOID;
                    PageHelper.GetControlValue<T_SURVEY_ITEM_Entity>(this.plITEMS, ref entity);
                    entity.ITEM_TYPE = StringHelper.ToInt(ddlITEM_TYPE.SelectedValue);
                    entity.SURVEY_ID = StringHelper.ToInt(txtSURVEY_ID1.Text);
                    iBll.Update(entity);
                }
                PageHelper.ShowMessage(this.Page, "保存成功！");
                Response.Redirect(HttpContext.Current.Request.RawUrl);
            }
        }

        private void Save_from_Items()
        {
            string s_id = txtSURVEY_ID1.Text;
            string i_id = txtITEM_ID.Text;
            string item_name = txtSELECTITEMS.Text;
            T_SURVEY_ITEMS_Entity isEntity = new T_SURVEY_ITEMS_Entity();
            isEntity = isBll.GetEntity("ITEM_NAME", item_name);
            if (isEntity == null)
            {
                PageHelper.ShowMessage(this.Page, "当前题库中不存在题目" + item_name + "，请从题库中选择题目！");
                return;
            }
            else
            {
                T_SURVEY_ITEM_Entity iEntity = new T_SURVEY_ITEM_Entity();
                long count = iBll.GetCount(" AND SURVEY_ID='" + s_id + "' and ITEM_NAME='" + item_name + "'");
                if (count > 0)
                {
                    PageHelper.ShowMessage(this.Page, "当前问卷中已存在题目" + item_name + "，请核实后再进行增加");
                    return;
                }
                iEntity = iBll.GetList(" AND SURVEY_ID='" + s_id + "' and ITEM_ID='" + i_id + "'").FirstOrDefault();
                if (iEntity == null)
                {
                    iEntity = new T_SURVEY_ITEM_Entity();
                    PageHelper.GetControlValue(plITEMS, ref iEntity);
                    iEntity.SURVEY_ID = StringHelper.ToInt(s_id);
                    iEntity.ITEM_TYPE = isEntity.ITEM_TYPE;
                    iEntity.ENINPUT = isEntity.ENINPUT;
                    iEntity.ITEM_NAME = item_name;
                    iEntity.BUSINESSDIVISIONCODE = _userLoginInfo.UserEntity.BUSINESSDIVISIONCODE;
                    iEntity.BUSINESSDIVISIONID = _userLoginInfo.UserEntity.BUSINESSDIVISIONID;
                    iEntity.BUSINESSDIVISIONNAME = _userLoginInfo.UserEntity.BUSINESSDIVISIONNAME;
                    iBll.Insert(iEntity);
                }
                else
                {
                    PageHelper.GetControlValue(plITEMS, ref iEntity);
                    iEntity.SURVEY_ID = StringHelper.ToInt(s_id);
                    iEntity.ITEM_TYPE = isEntity.ITEM_TYPE;
                    iEntity.ENINPUT = isEntity.ENINPUT;
                    iEntity.ITEM_NAME = item_name;
                    iBll.Update(iEntity);
                }
                //将原来的题目选项清空
                T_SURVEY_ITEM_OPTION_Entity siopEntity = new T_SURVEY_ITEM_OPTION_Entity();
                siopBll.Delete(" AND ITEM_ID = " + i_id + " and SURVEY_ID = " + s_id);
                List<T_SURVEY_OPTIONS_Entity> lsisopEntity = new List<T_SURVEY_OPTIONS_Entity>();
                lsisopEntity = isopBll.GetList(" AND ITEM_ID='" + isEntity.AUTOID.ToString()+ "'");
                foreach (T_SURVEY_OPTIONS_Entity isopEntity in lsisopEntity)
                {
                    siopEntity = new T_SURVEY_ITEM_OPTION_Entity();
                    siopEntity.OPTION_ID = isopEntity.OPTION_ID;
                    siopEntity.ITEM_ID = StringHelper.ToInt(i_id);
                    siopEntity.SURVEY_ID = StringHelper.ToInt(s_id);
                    siopEntity.OPTION_NAME = isopEntity.OPTION_NAME;
                    siopEntity.NEXT_ITEM = 0;
                    siopEntity.BUSINESSDIVISIONCODE = _userLoginInfo.UserEntity.BUSINESSDIVISIONCODE;
                    siopEntity.BUSINESSDIVISIONID = _userLoginInfo.UserEntity.BUSINESSDIVISIONID;
                    siopEntity.BUSINESSDIVISIONNAME = _userLoginInfo.UserEntity.BUSINESSDIVISIONNAME;
                    siopBll.Insert(siopEntity);
                }
            }
        }

        /// <summary>
        /// 设定题目选项
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSETITEM_OPTIONS_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(txtSURVEY_ID1.Text))
            {
                PageHelper.ShowMessage(this.Page, "问卷编号不能为空，请选择需要操作的问卷！");
                return;
            }
            if (string.IsNullOrEmpty(txtITEM_ID.Text))
            {
                PageHelper.ShowMessage(this.Page, "题目编号不能为空，请选择需要操作的问卷题目！");
                return;
            }
            if (String.IsNullOrEmpty(ddlITEM_TYPE.SelectedValue) || ddlITEM_TYPE.SelectedValue == ((int)ItemType.问答).ToString())
            {
                PageHelper.ShowMessage(this.Page, "题目类型为空或问答，不能做设定题目选项操作！");
                return;
            }
            T_SURVEY_ITEM_Entity entity = new T_SURVEY_ITEM_Entity();
            entity = iBll.GetList(String.Format(" AND SURVEY_ID='{0}' AND ITEM_ID='{1}'", txtSURVEY_ID1.Text, txtITEM_ID.Text)).FirstOrDefault();
            if (entity == null)
            {
                PageHelper.ShowMessage(this.Page, "请先保存问卷题目，再做设定题目选项操作！");
                return;
            }
            Response.Redirect(String.Format("SurveyItemOption.aspx?AUTOID={0}&SURVEY_ID={1}&ITEM_ID={2}", "", txtSURVEY_ID1.Text, txtITEM_ID.Text));
        }

        #region GridView 事件
        /// <summary>
        /// GridView 删除事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvList_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            if (sender == this.gvList)
            {
                T_SURVEY_Entity entity = new T_SURVEY_Entity();
                entity.SURVEY_ID = int.Parse((sender as GridView).DataKeys[e.RowIndex].Values[0].ToString());
                long rel = sBll.Delete(entity);
                if (rel > 0)
                {
                    iBll.Delete("SURVEY_ID", entity.SURVEY_ID.ToString());
                    siopBll.Delete("SURVEY_ID", entity.SURVEY_ID.ToString());
                    Response.Redirect(HttpContext.Current.Request.RawUrl);
                }
                else
                {
                    PageHelper.ShowMessage(this.Page, "问卷删除失败！");
                }
            }
            else if (sender == this.gvList_items)
            {
                T_SURVEY_ITEM_Entity entity = new T_SURVEY_ITEM_Entity();
                entity.AUTOID = int.Parse((sender as GridView).DataKeys[e.RowIndex].Values[0].ToString());
                long rel = iBll.Delete(entity);
                if (rel > 0)
                {
                    Response.Redirect(HttpContext.Current.Request.RawUrl);
                }
                else
                {
                    PageHelper.ShowMessage(this.Page, "题目删除失败！");
                }
            }
        }

        /// <summary>
        /// GridView 行数据绑定事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvList_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (sender == this.gvList)
            {
                string temp = string.Empty;
                switch (e.Row.RowType)
                {
                    case DataControlRowType.DataRow:
                        {
                            GridView gv = (sender as GridView);
                            for (int i = 0; i < gv.Columns.Count; i++)
                            {
                                TemplateField tf = gv.Columns[i] as TemplateField;
                                if (tf != null)
                                {
                                    #region 存储值 转换成  显示值
                                    switch (tf.HeaderText)
                                    {
                                        case "操作":
                                            {
                                                e.Row.Cells[i].Attributes.Add("style", "white-space: nowrap;");
                                            }
                                            break;
                                        default:
                                            {
                                                e.Row.Cells[i].Attributes.Add("style", "white-space: nowrap;");
                                            }
                                            break;
                                    }
                                    #endregion
                                }

                                BoundField bf = gv.Columns[i] as BoundField;
                                if (bf != null)
                                {
                                    #region 存储值 转换成  显示值

                                    

                                    #endregion
                                }
                            }
                        }
                        break;
                    case DataControlRowType.Header:
                        {

                        }
                        break;
                    case DataControlRowType.Pager:
                        {

                        }
                        break;
                    case DataControlRowType.EmptyDataRow:
                        {


                        }
                        break;
                    default:

                        break;
                }
            }
            else if (sender == this.gvList_items)
            {
                string temp = string.Empty;
                switch (e.Row.RowType)
                {
                    case DataControlRowType.DataRow:
                        {
                            GridView gv = (sender as GridView);
                            for (int i = 0; i < gv.Columns.Count; i++)
                            {
                                TemplateField tf = gv.Columns[i] as TemplateField;
                                if (tf != null)
                                {
                                    #region 存储值 转换成  显示值

                                    switch (tf.HeaderText)
                                    {
                                        case "操作":
                                            {
                                                e.Row.Cells[i].Attributes.Add("style", "white-space: nowrap;");
                                            }
                                            break;
                                        default:
                                            {
                                                e.Row.Cells[i].Attributes.Add("style", "white-space: nowrap;");
                                            }
                                            break;

                                    }

                                    #endregion
                                }

                                BoundField bf = gv.Columns[i] as BoundField;
                                if (bf != null)
                                {
                                    #region 存储值 转换成  显示值
                                    switch (bf.DataField)
                                    {
                                        case "ITEM_TYPE":
                                            try
                                            {
                                                temp = e.Row.Cells[i].Text.Trim();
                                                temp = ((ItemType)Enum.Parse(typeof(ItemType), temp)).ToString();
                                                e.Row.Cells[i].Text = temp;
                                            }
                                            catch (Exception)
                                            {

                                                //throw;
                                            }
                                            break;
                                        case "ENINPUT":
                                            try
                                            {
                                                temp = e.Row.Cells[i].Text.Trim();
                                                temp = ((IsEninput)Enum.Parse(typeof(IsEninput), temp)).ToString();
                                                e.Row.Cells[i].Text = temp;
                                            }
                                            catch (Exception)
                                            {

                                                //throw;
                                            }
                                            break;
                                        case "ENNULL":
                                            try
                                            {
                                                temp = e.Row.Cells[i].Text.Trim();
                                                temp = ((IsEnnull)Enum.Parse(typeof(IsEnnull), temp)).ToString();
                                                e.Row.Cells[i].Text = temp;
                                            }
                                            catch (Exception)
                                            {

                                                //throw;
                                            }
                                            break;
                                        default:
                                            {

                                            }
                                            break;
                                    }
                                    #endregion
                                }
                            }
                        }
                        break;
                    case DataControlRowType.Header:
                        {

                        }
                        break;
                    case DataControlRowType.Pager:
                        {

                        }
                        break;
                    case DataControlRowType.EmptyDataRow:
                        {


                        }
                        break;
                    default:

                        break;
                }
            }

        }

        /// <summary>
        /// GridView 行创建事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvList_RowCreated(object sender, GridViewRowEventArgs e)
        {
            switch (e.Row.RowType)
            {
                case DataControlRowType.DataRow:
                    {

                    }
                    break;
                case DataControlRowType.Header:
                    {

                    }
                    break;
                case DataControlRowType.Pager:
                    {

                    }
                    break;
                case DataControlRowType.EmptyDataRow:
                    {


                    }
                    break;
                default:

                    break;
            }

        }
        #endregion

        protected void btnSurveyShow_Click(object sender, EventArgs e)
        {
            Response.Redirect(String.Format("SurveyShow.aspx?Survey_ID='{0}'", txtSURVEY_ID.Text));
        }
    }
}
